/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.common.core.auth.client.config;

import cn.hutool.core.util.StrUtil;
import com.medusa.gruul.common.core.auth.client.helper.ISecurity;
import com.medusa.gruul.common.core.auth.model.User;
import com.medusa.gruul.common.core.auth.model.constant.Headers;
import com.medusa.gruul.common.core.auth.model.constant.Keys;
import com.medusa.gruul.common.core.helper.RedisKeyHelper;
import com.medusa.gruul.common.redis.RedisManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author 张治保
 * date 2022/1/7
 */
@Slf4j
@ControllerAdvice
public class LastModifyTimeResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        User user = ISecurity.user().can();
        if (user == null){
            return body;
        }
        String lastModifyTimeStr = RedisManager.getInstance().get(RedisKeyHelper.key(Keys.USER_LAST_MODIFY_TIME, user.getUserId()));
        if (StrUtil.isBlank(lastModifyTimeStr)){
            return body;
        }
        log.info("LastModifyTimeResponseAdvice 设置响应头");
        response.getHeaders().set(Headers.LAST_MODIFY_TIME,lastModifyTimeStr);
        return body;
    }
}
